# -*- coding:utf-8 -*-

import binascii, struct


class unPack(object):
    def __init__(self, socket):
        self.socket = socket
        self.factory = socket.factory
        self.allData = ''

    def unpackage(self, newData):
        self.allData = self.allData + newData  # 所有数据
        data = self.allData
        realy_pack_len = len(data)

        while realy_pack_len > 0:
            try:
                hex_str = binascii.b2a_hex(data[0:10])  # 将可能为包头的数据转换为hex
                pack_len = int(binascii.a2b_hex(hex_str[0:4]))  # 获取包头

                head_len = len(str(pack_len))  # 包头长度

                # 1：包头长度， 2：包长度， 3：剩余数据长度
                pack_format = '%ds%ds%ds' % (head_len, pack_len, len(data) - (pack_len + head_len))
                pack_len, run_data, data = struct.unpack(pack_format, data)
                realy_pack_len = len(data)
                self.allData = data
                self.factory.filiter.requestCheck(run_data, self.socket)
            except Exception, e:
                print "包缺失，等待中......"
                return
